package ru.spb.osll.myfit.client.widget;

import com.google.gwt.user.client.ui.MouseListenerAdapter;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.RootPanel;

public class TooltipMouseListener extends MouseListenerAdapter {
    public static final int ST_NORMAL = 0;
    public static final int ST_STICKY = 1;
    public static final int ST_FORCE_HIDE = 2;
    
    private int state;
    private Tooltip mobileTooltip;
    
    public TooltipMouseListener(Tooltip mobileTooltip){
        this.mobileTooltip = mobileTooltip;
        this.state = ST_NORMAL;
    }
    
    public void onMouseEnter(Widget sender) {
        if(this.state != ST_STICKY && this.state != ST_FORCE_HIDE){
            this.state = ST_NORMAL;
            mobileTooltip.show();
        }
        
    }
    public void onMouseMove(Widget sender, int x, int y) {
        //only update the position of the tooltip in NORMAL state
        if(this.state == ST_FORCE_HIDE || this.state == ST_STICKY){
            return;
        }
        
        //calculate the posistion of the mouse pointer
        //relative to the client window
        mobileTooltip.setPopupPosition(
                this.getDisplayLocationX(sender, x),
                this.getDisplayLocationY(sender, y));
    }
    
    private int getDisplayLocationX(Widget sender, int x){
        return sender.getAbsoluteLeft() + x +
                getPageScrollLeft() + mobileTooltip.getOffsetX();
    }
    
    private int getDisplayLocationY(Widget sender, int y){
        return sender.getAbsoluteTop() + y +
                getPageScrollTop() + mobileTooltip.getOffsetY();
    }
    
    public void onMouseDown(Widget sender, int x, int y) {
        if(this.state == ST_STICKY){
            mobileTooltip.hide();
            this.state = ST_FORCE_HIDE;
            return;
        }
        mobileTooltip.setPopupPosition(
                this.getDisplayLocationX(sender, x),
                this.getDisplayLocationY(sender, y));
        if(this.state == ST_FORCE_HIDE){
            mobileTooltip.show();
            this.state = ST_NORMAL;
        }else if(this.state == ST_NORMAL){
            mobileTooltip.show();
            this.state = ST_STICKY;
        }
    }
    
    public void onMouseLeave(Widget sender) {
        if(this.state != ST_STICKY){
            mobileTooltip.hide();
        }
    }
    
    /**
     * Get the offset for the horizontal scroll
     */
    private int getPageScrollTop() {
        return DOM.getAbsoluteTop(
                DOM.getParent( RootPanel.getBodyElement()));
    }
    
    /**
     * Get the offset for the vertical scroll
      */
    private int getPageScrollLeft() {
        return DOM.getAbsoluteLeft(
                DOM.getParent( RootPanel.getBodyElement()));
    }
}